package com.redis.service.impl;

import com.redis.entity.Concert;
import com.redis.mapper.ConcertMapper;
import com.redis.service.PreheatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 13205
 * @Date: 2024/12/23 21:03
 * @Description:
 */

@Service
public class PreheatServiceImpl implements PreheatService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ConcertMapper concertMapper;

    public void preheatAllConcertData() {
        // 从数据库加载所有演唱会数据
        List<Concert> concerts = concertMapper.getAllConcert();

        // 遍历并将数据写入 Redis
        for (Concert concert : concerts) {
            String key = "concert:" + concert.getCid();
            redisTemplate.opsForValue().set(key, concert.getTickets());

            // 设置随机过期时间，防止缓存雪崩
            int randomExpiry = 360 + new Random().nextInt(100);
            redisTemplate.expire(key, randomExpiry, TimeUnit.SECONDS);
        }

        System.out.println("Redis 演唱会缓存预热完成");
    }

    public void preheatConcertData(Integer cid){
        Concert concert = concertMapper.getById(cid);
        String key = "concert:" + concert.getCid();
        redisTemplate.opsForValue().set(key, concert.getTickets());

        // 设置随机过期时间，防止缓存雪崩
        int randomExpiry = 360 + new Random().nextInt(100);
        redisTemplate.expire(key, randomExpiry, TimeUnit.SECONDS);

    }
}
